package ws.jdbc.concurrent.driver.sqlserver

import java.sql.*
import ws.jdbc.concurrent.driver.sqlserver.tds.*

/**
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
class ResultSetTest extends GroovyTestCase {
  /** URL to connect to the SQL Server. */
  String url = "jdbc:sqlserver://localhost:1433;username=sa;password=sg4765j;database=JDBCDriverTests"
  /** Connection with the SQL Server. */
  Connection con
  /** Object used on the tests. */
  ResultSet rs
  /** SQL query to create the result set. */
  String sqlQuery = "Select * from Table1"
  /** Number of created threads during the cursor tests. */
  def nthreads = 20
  def stmt
  def rand = new Random()
  
  ResultSetTest() {
    con = DriverManager.getConnection(url)
  }

  void setUp() throws IOException {
    println "-----------------------------------------------------------------"

    def stmt = con.createStatement()
    stmt.executeUpdate("DELETE FROM Table1")

    DataTest.table.each() {
      stmt.executeUpdate("INSERT INTO Table1 VALUES(" + it[0] + ",'" + it[1] + "')")
    }

    stmt.close()
  }

  void assertLineValuesMatch(rs, lineNumber) {
    assertEquals "Wrong current row.", lineNumber , rs.getRow()
    assertEquals "Col1 values on line " + lineNumber + " don't match.", DataTest.table[lineNumber - 1][0], rs.getInt(1)
    assertEquals "Col2 values on line " + lineNumber + " don't match.", DataTest.table[lineNumber - 1][1], rs.getString(2)
  }

  void assertLineValuesMatch(rs, lineNumber, col1, col2) {
    assertEquals "Wrong current row.", lineNumber , rs.getRow()
    assertEquals "Col1 values on line " + lineNumber + " don't match.", col1, rs.getInt(1)
    assertEquals "Col2 values on line " + lineNumber + " don't match.", col2, rs.getString(2)
  }

  void printLine() {
    printf("%6d|%4d|  %s\n", rs.getRow(), rs.getInt(1), rs.getString(2))
  }

  void printLine(ResultSet rs) {
    printf("%6d|%4d|  %s\n", rs.getRow(), rs.getInt(1), rs.getString(2))
  }

  def runThreads(closure) {
    def tlist = new Thread[nthreads]

    nthreads.times {
      tlist[it] = Thread.start {
        closure()
      }
    }

    nthreads.times {
      tlist[it].join()
    }
  }

  def assertResultSetEquals(row = 1, inc = true, rs, scroll) {
    def count = 0
    while(scroll()) {
      //      printLine()

      assertLineValuesMatch rs, row
      if(inc) {
        row++
      } else {
        row--
      }
      count++
    }
    assertEquals DataTest.table.size(), count
    assertEquals CResultSet.ROW_BEFORE, rs.getRow()
  }
}